/**
 * WebSocket服务
 * 用于建立实时通信连接，实现类似ChatGPT的实时对话功能
 */

// WebSocket连接地址
const WS_URL = 'wss://adminstore.saas.nbsaas.com/websocket';

// WebSocket实例
let socketTask = null;

// 心跳检测相关变量
let heartbeatInterval = null;
const HEARTBEAT_INTERVAL = 30000; // 30秒发送一次心跳
const RECONNECT_INTERVAL = 5000; // 5秒重连一次
let reconnectTimer = null;
let isConnecting = false;

// 消息回调函数
let messageCallback = null;
let openCallback = null;
let closeCallback = null;
let errorCallback = null;
let reconnectCallback = null;

/**
 * 初始化WebSocket连接
 * @param {Object} options - 配置选项
 * @param {Function} options.onMessage - 消息回调函数
 * @param {Function} options.onOpen - 连接成功回调函数
 * @param {Function} options.onClose - 连接关闭回调函数
 * @param {Function} options.onError - 连接错误回调函数
 * @param {Function} options.onReconnect - 重连回调函数
 */
export const initWebSocket = (options = {}) => {
    if (isConnecting) return;
    isConnecting = true;
    
    // 保存回调函数
    messageCallback = options.onMessage;
    openCallback = options.onOpen;
    closeCallback = options.onClose;
    errorCallback = options.onError;
    reconnectCallback = options.onReconnect;
    
    if (socketTask) {
        socketTask.close();
        socketTask = null;
    }
    
    // 创建WebSocket连接
    try {
        socketTask = uni.connectSocket({
            url: `${WS_URL}?token=${uni.getStorageSync('token')}`,
            success: () => {
                console.log('WebSocket连接创建成功');
            },
            fail: (error) => {
                console.error('WebSocket创建失败:', error);
                reconnect();
            }
        });
        
        // 监听连接打开
        socketTask.onOpen((res) => {
            console.log('WebSocket连接已打开', res);
            isConnecting = false;
            clearTimeout(reconnectTimer);
            startHeartbeat();
            if (openCallback) openCallback(res);
        });
        
        // 监听消息
        socketTask.onMessage((res) => {
            let message;
            try {
                // 尝试解析JSON
                message = JSON.parse(res.data);
            } catch (e) {
                // 如果不是JSON，则直接使用原始数据
                message = res.data;
            }
            
            // 如果是心跳回应，不处理
            if (message?.type === 'heartbeat') {
                return;
            }
            
            // 调用消息回调
            if (messageCallback) messageCallback(message);
        });
        
        // 监听连接关闭
        socketTask.onClose((res) => {
            console.log('WebSocket连接已关闭', res);
            isConnecting = false;
            clearInterval(heartbeatInterval);
            socketTask = null;
            
            if (closeCallback) closeCallback(res);
            reconnect();
        });
        
        // 监听连接错误
        socketTask.onError((error) => {
            console.error('WebSocket连接错误', error);
            isConnecting = false;
            if (errorCallback) errorCallback(error);
            reconnect();
        });
    } catch (error) {
        console.error('WebSocket创建异常:', error);
        isConnecting = false;
        reconnect();
    }
};

/**
 * 重新连接
 */
const reconnect = () => {
    if (socketTask && socketTask.readyState !== 3) return;
    
    clearTimeout(reconnectTimer);
    reconnectTimer = setTimeout(() => {
        console.log('尝试重新连接WebSocket...');
        if (reconnectCallback) reconnectCallback();
        initWebSocket({
            onMessage: messageCallback,
            onOpen: openCallback,
            onClose: closeCallback,
            onError: errorCallback,
            onReconnect: reconnectCallback
        });
    }, RECONNECT_INTERVAL);
};

/**
 * 开始发送心跳包
 */
const startHeartbeat = () => {
    clearInterval(heartbeatInterval);
    heartbeatInterval = setInterval(() => {
        sendMessage({
            type: 'heartbeat',
            timestamp: Date.now()
        });
    }, HEARTBEAT_INTERVAL);
};

/**
 * 发送消息
 * @param {Object|String} data - 要发送的数据
 * @returns {Promise} - 返回Promise对象
 */
export const sendMessage = (data) => {
    return new Promise((resolve, reject) => {
        if (!socketTask || socketTask.readyState !== 1) {
            reject('WebSocket未连接');
            reconnect();
            return;
        }
        
        let message = data;
        if (typeof data === 'object') {
            message = JSON.stringify(data);
        }
        
        socketTask.send({
            data: message,
            success: (res) => {
                resolve(res);
            },
            fail: (error) => {
                console.error('发送WebSocket消息失败:', error);
                reject(error);
            }
        });
    });
};

/**
 * 关闭WebSocket连接
 */
export const closeWebSocket = () => {
    if (socketTask) {
        clearInterval(heartbeatInterval);
        clearTimeout(reconnectTimer);
        
        socketTask.close({
            success: (res) => {
                console.log('WebSocket连接已关闭', res);
            },
            fail: (error) => {
                console.error('关闭WebSocket连接失败:', error);
            }
        });
        
        socketTask = null;
    }
};

/**
 * 检查WebSocket连接状态
 * @returns {Boolean} - 返回连接状态，true表示已连接，false表示未连接
 */
export const isWebSocketConnected = () => {
    return socketTask && socketTask.readyState === 1;
};

export default {
    initWebSocket,
    sendMessage,
    closeWebSocket,
    isWebSocketConnected
}; 